<script lang="ts" setup>
import type { FormInstance } from 'ant-design-vue';
import type { Rule } from 'ant-design-vue/es/form';

import { onMounted, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { Apis } from '#/api';
import { DICT_TYPE, dictUtils } from '#/utils/dict';

const emit = defineEmits(['success']);

export interface EditDictTypeModalState {
  isUpdate: boolean;
  record: Record<string, any>;
}
type ModalState = EditDictTypeModalState;

const data = ref<ModalState>({
  isUpdate: false,
  record: {},
});

const dictMap = ref<any>({});

const form = ref({
  parentId: '',
  name: '',
  code: '',
  status: 0,
  remark: '',
});

const formRef = ref<FormInstance>();

const isLoading = ref(false);

const rules: Record<string, Rule[]> = {
  parentId: [{ required: true, message: '请选择父级字典类型' }],
  name: [{ required: true, message: '请填写类型名称' }],
  code: [{ required: true, message: '请填写类型编码' }],
};

const parentDictTypeList = ref<any[]>([]);

const [BaseModal, baseModalApi] = useVbenModal({
  onOpenChange: async (isOpen: boolean) => {
    if (isOpen) {
      data.value = baseModalApi.getData<ModalState>();

      if (data.value.record) {
        form.value = {
          ...form.value,
          ...data.value.record,
        };
      }

      {
        const res = await Apis.system.dictType.getList({
          params: {
            parentId: '0',
          },
        });
        parentDictTypeList.value = res.list;
        parentDictTypeList.value.unshift({
          id: '0',
          name: '无',
        });
        parentDictTypeList.value.forEach((item) => {
          item.label = item.name;
          item.value = item.id;
        });
        form.value.parentId = form.value.parentId || '0';
      }

      initForm();
    }
  },
  onConfirm: onSubmit,
});

async function onSubmit() {
  await formRef.value!.validate();

  try {
    isLoading.value = true;

    if (data.value.isUpdate) {
      await Apis.system.dictType.update({
        pathParams: {
          id: data.value.record.id,
        },
        data: form.value,
      });
    }

    if (!data.value.isUpdate) {
      await Apis.system.dictType.add({
        data: form.value,
      });
    }

    message.success({
      content: `操作成功`,
    });

    baseModalApi.close();
    emit('success');
  } catch (error) {
    message.error(`${data.value.isUpdate ? '修改' : '新增'}字典类型失败`);
    console.error('表单验证失败:', error);
  } finally {
    isLoading.value = false;
  }
}

function initForm() {
  const defaultStatus = dictUtils.getDictDefaultObjByOptions(
    dictMap.value[DICT_TYPE.sysCommonStatus],
  )?.value;
  form.value.status = form.value.status ?? defaultStatus;
}

onMounted(async () => {
  dictMap.value = await dictUtils.getDictDatasAsync([
    { type: DICT_TYPE.sysCommonStatus, valueType: 'number' },
    { type: DICT_TYPE.sysCommonWhether, valueType: 'number' },
    { type: DICT_TYPE.sysCommonColorType, valueType: 'string' },
  ]);
  initForm();
});
</script>
<template>
  <BaseModal
    :confirm-loading="isLoading"
    :title="data.isUpdate ? '修改字典类型' : '新增字典类型'"
    class="w-[600px]"
  >
    <a-form
      ref="formRef"
      :label-col="{ style: 'width: 120px' }"
      :model="form"
      :rules="rules"
      class="grid-cols-1"
      label-class="w-full"
      layout="horizontal"
    >
      <a-form-item label="父级字典" name="parentId">
        <a-select
          v-model:value="form.parentId"
          :options="parentDictTypeList"
          class="w-full"
          placeholder="请选择父级字典"
        />
      </a-form-item>

      <a-form-item label="类型名称" name="name">
        <a-input
          v-model:value="form.name"
          class="w-full"
          max-length="50"
          placeholder="请填写类型名称"
        />
      </a-form-item>

      <a-form-item label="类型编码" name="code">
        <a-input
          v-model:value="form.code"
          class="w-full"
          max-length="50"
          placeholder="请填写类型编码"
        />
      </a-form-item>

      <a-form-item label="记录状态" name="status">
        <a-radio-group
          v-model:value="form.status"
          :options="dictMap[DICT_TYPE.sysCommonStatus]"
          class="w-full"
        />
      </a-form-item>

      <a-form-item label="备注" name="remark">
        <a-textarea
          v-model:value="form.remark"
          :auto-size="{ minRows: 3, maxRows: 5 }"
          class="w-full"
          max-length="200"
          placeholder="请填写备注"
        />
      </a-form-item>
    </a-form>
  </BaseModal>
</template>
